package com.temp.controller.user;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.temp.dto.ChatMessageDTO;
import com.temp.entity.ChatMessage;
import com.temp.entity.User;
import com.temp.result.Result;
import com.temp.service.ChatMessageService;
import com.temp.utils.ShiroUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

@RestController
@RequestMapping("/api/chat")
@Api(tags = "聊天相关接口")
@Slf4j
@Validated
public class ChatController {

    @Autowired
    private ChatMessageService chatMessageService;

    @GetMapping("/query")
    @ApiOperation("获取聊天记录")
    @RequiresPermissions("user:chat:query")
    public Result getHistory() {
        User user = ShiroUtils.getUser();
        List<ChatMessage> list = chatMessageService.list(Wrappers.<ChatMessage>lambdaQuery()
                .eq(ChatMessage::getSenderId, user.getId())
                .or()
                .eq(ChatMessage::getReceiverId, user.getId())
                .orderByAsc(ChatMessage::getCreatedAt));
        return Result.success(list,"apiMsg.querySuccess");
    }

    @PostMapping("/add")
    @ApiOperation("用户保存消息")
    @RequiresPermissions("user:chat:add")
    public Result addChatMessage(@Valid @RequestBody ChatMessageDTO chatMessageDTO) {
        ChatMessage chatMessage = new ChatMessage();
        BeanUtils.copyProperties(chatMessageDTO,chatMessage);
        boolean isSuccess = chatMessageService.save(chatMessage);

        return isSuccess ? Result.success(chatMessage,"apiMsg.optionSuccess") : Result.error("apiMsg.optionError");
    }
}
